// 修正导入部分，移除不存在的FormItem
import React, { useState, useMemo, useCallback } from 'react';
import { 
  RadioGroup, 
  Radio, 
  TextArea, 
  Button, 
  Upload, 
  Modal, 
  Checkbox, 
  // Form, 
  Select, Col, Row
} from '@douyinfe/semi-ui';
import { Image, Select as ArcoSelect, Form, Message } from '@arco-design/web-react';
import styles from "./videoConfig.module.scss";
import VideoSelectConfig from '@/pages/video/common/videoSelectConfig';
import { textToVideo } from '@/api/video';
import { useLoading } from '@/components/common/mlsLoading/laodingText';
import { ICON_PATHS } from '@/assets/images/constants';
const FormItem = Form.Item;

const MENU_HEIGHTS = {
  pic: { area: '353px', textArea: '360px' },
  multi: { area: '134px', textArea: '224px' },
  image: { area: '227px' },
  default: { area: '', textArea: '' }
};

export default function MainEdit({
  currentMenuKey,
  currentMenuTitle,
}) {
  // 获取高度配置
  const heights = MENU_HEIGHTS[currentMenuKey] || MENU_HEIGHTS.default;

  // 添加分镜配置弹窗状态
  const [storyboardModalVisible, setStoryboardModalVisible] = useState(false);
  const [promptText, setPromptText] = useState('');
  const [ratio, setRatio] = useState('16:9');
  const [resolution, setResolution] = useState('1080p');
  const [duration, setDuration] = useState('short');
  const [deviceApi, setDeviceApi] = useState(undefined);
  const [deviceApiLabel, setDeviceApiLabel] = useState(undefined);
  const { showLoading, hideLoading } = useLoading();
  
  // 分镜表单数据状态
  const [storyboardForm, setStoryboardForm] = useState({
    script: '',        // 剧本
    storyUnit: '',     // 故事单元
    scene: '',         // 场景
    shotNumber: '',    // 镜号
    prompt: ''         // 分镜视频提示词
  });
  
  // 模拟数据选项
  const scriptOptions = [
    { label: '剧本1', value: 'script1' },
    { label: '剧本2', value: 'script2' },
    { label: '剧本3', value: 'script3' }
  ];
  
  const storyUnitOptions = [
    { label: '单元1', value: 'unit1' },
    { label: '单元2', value: 'unit2' },
    { label: '单元3', value: 'unit3' }
  ];
  
  const sceneOptions = [
    { label: '场景1', value: 'scene1' },
    { label: '场景2', value: 'scene2' },
    { label: '场景3', value: 'scene3' }
  ];
  
  const shotNumberOptions = [
    { label: '1镜', value: 'shot1' },
    { label: '2镜', value: 'shot2' },
    { label: '3镜', value: 'shot3' },
    { label: '4镜', value: 'shot4' },
    { label: '5镜', value: 'shot5' }
  ];
  
  // 打开分镜配置弹窗
  const openStoryboardModal = () => {
    console.log('currentMenuKey', 1) 
    setStoryboardModalVisible(true);
  };
  
  // 关闭分镜配置弹窗
  const closeStoryboardModal = () => {
    setStoryboardModalVisible(false);
  };
  
  // 处理表单字段变化
  const handleFormChange = (field, value) => {
    // console.log('field', field, 'value', value);
    
    setStoryboardForm(prev => ({
      ...prev,
      [field]: value
    }));
  };
  
  // 确认使用分镜配置
  const confirmStoryboardConfig = () => {
    // 这里可以添加处理分镜配置的逻辑
    console.log('使用分镜配置:', storyboardForm);
    
    // 关闭弹窗
    closeStoryboardModal();
  };

  // 渲染参考提示词区域
  const renderReferencePromptSection = useCallback(
    (placeholder = '请在此输入提示词，描述视频内容...') => (
      <>
        <div className={styles.titleSection}>参考提示词</div>
        <div className={styles.area} style={{ maxHeight: heights.textArea }}>
          <TextArea value={promptText} placeholder={placeholder} onChange={changePromptText} />

          <div className={styles.opts}>
            <Image
              className={styles.img}
              src={ICON_PATHS.DELETE_ICON}
              preview={false}
              draggable={false}
              onClick={() => {
                setPromptText(undefined);
              }}
            />
            {/* <div className={styles.opt} onClick={openStoryboardModal} style={{ cursor: 'pointer' }}>
            <Image src={text_mirror} preview={false} draggable={false} />
            <div className={styles.text}>使用分镜脚本</div>
          </div> */}
          </div>
        </div>
      </>
    ),
    [heights.textArea, promptText, setPromptText]
  );
  
  const savePrit = (e) => {
    console.log(e)
  }

  // 渲染工具按钮
  const renderToolButtons = () => {
    return <div></div>;
  };

  const changePromptText = useCallback(
    value => {
      setPromptText(value);
    },
    [setPromptText]
  );

  const generateVideo = useCallback(() => {
    console.log('generateVideo', promptText);
    if (!promptText) {
      Message.error('请输入提示词');
      return;
    }
    if (!deviceApi) {
      Message.error('请选择API');
      return;
    }

    let obj = {
      text: promptText,
      ratio,
      resolution,
      api: deviceApi,
      apiName: deviceApiLabel,
      duration,
    }
    showLoading('生成中...');
    textToVideo(obj).then(res => {
      console.log('textToVideo', res);
    }).catch(err => {
      console.log('textToVideo err', err);
      hideLoading();
    })

  }, [promptText, ratio, resolution, deviceApi, duration]);

  const onDeviceApiChange = useCallback(
    ({value, label}) => {
      console.log('onDeviceApiChange', value, label);
      
      setDeviceApi(value);
      setDeviceApiLabel(label);
    },
    [setDeviceApi, setDeviceApiLabel]
  );

  return (
    <div className={styles.mainEdit}>
      <div className={styles.top}>
        <div className={styles.header}>
          <div className={styles.title}>{currentMenuTitle}</div>
        </div>
        {renderReferencePromptSection()}

        {/* <Checkbox className={styles.saveBtn} onChange={savePrit} aria-label="保存脚本修改">
          保存脚本修改
        </Checkbox> */}

        {/* {currentMenuKey === 'image' && (
          <div className={styles.imageContainer}>
            {renderToolButtons()}
            <div></div>
          </div>
        )} */}
        {/* {['image', 'layer'].includes(currentMenuKey) && (
          <div className={styles.submitButtonContainer}>
            <Button className={`button buttonPrimary ${styles.submitButton}`}>提交</Button>
          </div>
        )} */}
      </div>
      {
        <div className={styles.bottom}>
          <VideoSelectConfig
            duration={duration}
            onDurationChange={setDuration}
            resolution={resolution}
            onResolutionChange={setResolution}
            ratio={ratio}
            onRatioChange={setRatio}
            deviceApi={deviceApi}
            onDeviceApiChange={onDeviceApiChange}
            onGenerate={generateVideo}
          />
        </div>
      }

      {/* 分镜配置弹窗 - 使用Arco组件改造 */}
      <Modal
        title="分镜脚本"
        visible={storyboardModalVisible}
        footer={
          <div className={styles.historyModalButton}>
            {/* <Button 
            onClick={closeStoryboardModal} 
            className={`${styles.button} button buttonDefault`}
          >
            取消
          </Button> */}
            <Button
              onClick={confirmStoryboardConfig}
              className={`${styles.button} button buttonPrimary`}
              style={{ width: '100%', borderRadius: '8px' }}>
              确认
            </Button>
          </div>
        }
        width={600}
        centered>
        <div className={styles.storyboardModalContent}>
          <Form
            layout="horizontal"
            labelAlign="left"
            labelWidth={100}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            className={styles.formLayout}>
            <Row gutter={16}>
              {/* First row: Script and Story Unit */}
              <Col span={12}>
                <FormItem label="剧本:" field="script">
                  <ArcoSelect
                    value={storyboardForm.script}
                    onChange={value => handleFormChange('script', value)}
                    placeholder="请选择剧本"
                    style={{ width: '100%' }}>
                    {scriptOptions.map(option => (
                      <ArcoSelect.Option key={option.value} value={option.value}>
                        {option.label}
                      </ArcoSelect.Option>
                    ))}
                  </ArcoSelect>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="故事单元:" field="storyUnit">
                  <ArcoSelect
                    value={storyboardForm.storyUnit}
                    onChange={value => handleFormChange('storyUnit', value)}
                    placeholder="请选择故事单元"
                    style={{ width: '100%' }}>
                    {storyUnitOptions.map(option => (
                      <ArcoSelect.Option key={option.value} value={option.value}>
                        {option.label}
                      </ArcoSelect.Option>
                    ))}
                  </ArcoSelect>
                </FormItem>
              </Col>
            </Row>

            <Row gutter={16} style={{ marginTop: '16px' }}>
              {/* Second row: Scene and Shot Number */}
              <Col span={12}>
                <FormItem label="场景:" field="scene">
                  <ArcoSelect
                    value={storyboardForm.scene}
                    onChange={value => handleFormChange('scene', value)}
                    placeholder="请选择场景"
                    style={{ width: '100%' }}>
                    {sceneOptions.map(option => (
                      <ArcoSelect.Option key={option.value} value={option.value}>
                        {option.label}
                      </ArcoSelect.Option>
                    ))}
                  </ArcoSelect>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label="镜号:" field="shotNumber">
                  <ArcoSelect
                    value={storyboardForm.shotNumber}
                    onChange={value => handleFormChange('shotNumber', value)}
                    placeholder="请选择镜号"
                    style={{ width: '100%' }}>
                    {shotNumberOptions.map(option => (
                      <ArcoSelect.Option key={option.value} value={option.value}>
                        {option.label}
                      </ArcoSelect.Option>
                    ))}
                  </ArcoSelect>
                </FormItem>
              </Col>
            </Row>

            {/* Third row: Storyboard Video Prompt */}
            <Row style={{ marginTop: '16px' }}>
              <Col span={24}>
                <FormItem label="分镜视频提示词" field="prompt" layout="vertical">
                  <TextArea
                    placeholder="请输入分镜视频提示词..."
                    value={storyboardForm.prompt}
                    onChange={e => handleFormChange('prompt', e)}
                    autosize={{ minRows: 4, maxRows: 6 }}
                    className={styles.textArea}
                  />
                </FormItem>
              </Col>
            </Row>

            <Row style={{ marginTop: '12px' }}>
              <Col span={24}>
                <span style={{ fontSize: '14px', color: '#fff', opacity: 0.8 }}>
                  建议API：可灵２.１大师版
                </span>
              </Col>
            </Row>
          </Form>
        </div>
      </Modal>
    </div>
  );
}